package ynu.edu.rule;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.DefaultResponse;
import org.springframework.cloud.client.loadbalancer.EmptyResponse;
import org.springframework.cloud.client.loadbalancer.Request;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import reactor.core.publisher.Mono;

import java.util.List;

public class ThreeTimeLoadBalancer implements ReactorServiceInstanceLoadBalancer {
    private int instance_call_count = 0; //已经被调用的次数
    private int instance_index = 0;//当前提供服务的实例
    private final String serviceId;
    private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSuppliers;


    public ThreeTimeLoadBalancer(ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSuppliers, String serviceId) {
        this.serviceInstanceListSuppliers = serviceInstanceListSuppliers;
        this.serviceId = serviceId;
    }

    @Override
    public Mono<Response<ServiceInstance>> choose(Request request) {
        ServiceInstanceListSupplier supplier=this.serviceInstanceListSuppliers.getIfAvailable();
        return supplier.get().next().map(this::getInstanseResponse);
    }

    public synchronized Response<ServiceInstance> getInstanseResponse(List<ServiceInstance> instances) {
        if (instances.isEmpty()) {
            return new EmptyResponse();
        }

        // 总的服务实例数量
        int size = instances.size();
        ServiceInstance serviceInstance;

        if (instance_call_count < 3) {
            // 当前实例调用次数还未满3次，继续使用当前实例
            serviceInstance = instances.get(instance_index);
            instance_call_count++;
        } else {
            // 当前实例调用已满3次，切换到下一个实例
            instance_call_count = 0;
            instance_index++;
            if (instance_index >= size) {
                // 如果索引越界，则从第一个实例重新开始
                instance_index = 0;
            }
            serviceInstance = instances.get(instance_index);
            //切换实例后，立即增加新实例的调用次数
            instance_call_count++;
        }
        return new DefaultResponse(serviceInstance);
    }




}
